package es.udc.pfc.davidparedes.model.shift;

import java.util.Calendar;
import java.util.List;

import org.springframework.stereotype.Repository;

import es.udc.pfc.davidparedes.model.dao.GenericDaoHibernate;

@Repository("shiftDao")
public class ShiftDaoHibernate extends
		GenericDaoHibernate<Shift, Long> implements ShiftDao {
	
	@SuppressWarnings("unchecked")
	public List<Shift> findShiftsByDate(Long userProfileId, Calendar startDate, Calendar endDate) {
		return getSession()
				  .createQuery(
				  "SELECT s FROM Shift s WHERE "
				  + "s.manager.userProfileId = :userProfileId AND "
				  + "s.start >= :startDate AND s.end <= :endDate ORDER BY s.start")
				  .setParameter("userProfileId", userProfileId)
				  .setCalendar("startDate", startDate)
				  .setCalendar("endDate", endDate)
				  .list();
	}

	@SuppressWarnings("unchecked")
	public List<Shift> findUniverseShiftsByDate(Long universeId,
			Calendar startDate, Calendar endDate) {
		return getSession()
				.createQuery(
				"SELECT s FROM Shift s WHERE "
				+ "s.universe.universeId = :universeId AND "
				+ "s.start >= :startDate AND s.end <= :endDate ORDER BY s.start")
				.setParameter("universeId", universeId)
				.setCalendar("startDate", startDate)
				.setCalendar("endDate", endDate)
				.list();
	}

	@SuppressWarnings("unchecked")
	public List<Shift> findUniverseShiftsAtMoment(Long universeId, Calendar moment) {
		return getSession()
				.createQuery(
				"SELECT s FROM Shift s WHERE "
				+ "s.universe.universeId = :universeId AND "
				+ "s.start <= :moment AND s.end >= :moment ORDER BY s.start")
				.setParameter("universeId", universeId)
				.setCalendar("moment", moment)
				.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Shift> findStoreShiftsByDate(Long storeId, Calendar startDate, Calendar endDate){
		return getSession()
				.createQuery(
				"SELECT s FROM Shift s WHERE "
				+ "s.universe.store.storeId = :storeId AND "
				+ "s.start >= :startDate AND s.end <= :endDate ORDER BY s.start")
				.setParameter("storeId", storeId)
				.setCalendar("startDate", startDate)
				.setCalendar("endDate", endDate)
				.list();
	}

	public Long getTotalShiftsDuration(Long userProfileId, Calendar startDate,
			Calendar endDate) {
		
		Long result = (Long) getSession()
			  .createQuery(
			  "SELECT SUM(s.duration) FROM Shift s WHERE "
			  + "s.manager.userProfileId = :userProfileId AND "
			  + "s.start >= :startDate AND s.end <= :endDate "
			  + "GROUP BY s.manager")
			  .setParameter("userProfileId", userProfileId)
			  .setCalendar("startDate", startDate)
			  .setCalendar("endDate", endDate)
			  .uniqueResult();
		
		if (result == null) {
			result = (long) 0;
		}
		
		return result;
	}

}
